import socket
import struct

if __name__ == '__main__':
    tcp_server_socket = socket.socket()
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcp_server_socket.bind(("", 9001))
    tcp_server_socket.listen(128)
    new_client, ip_port = tcp_server_socket.accept()
    print("端口号", ip_port)
    name1 = ""
    while True:
        recv_data = new_client.recv(128)
        # 获取字符串的总长度
        s = struct.unpack('I', recv_data[4:8])
        b1, b2 = recv_data.split(b',')
        byProtocol, all_len, name, message = struct.unpack(f'cI{s[0] - len(b2)}s{len(b2)}s', recv_data)
        if byProtocol == b'T':
            byProtocol = "TCP"
        else:
            byProtocol = "UDP"
        print(f"采用协议{byProtocol},传输数据总长度{all_len},姓名:{name.decode('utf-8').split(',')[0]},说:{message.decode('utf-8')}")

        # byProtocol TCP
        # 姓名
        if name1 == "":
            name1 = input("请输入你的姓名")
            name1 = name1 + ','
            name1 = name1.encode("utf-8")
        # 内容
        message = input("请输入内容")
        message = message.encode("utf-8")
        # 长度
        all_len = len(name1) + len(message)
        values = (b'T', all_len, name1, message)
        s = struct.Struct(f'cI{len(name1)}s{len(message)}s')
        packed_data = s.pack(*values)
        new_client.send(packed_data)
    # 关闭服务端和客户端的套接字,表示和客户端停止通信
    new_client.close()
    # 7.关闭服务端套接字,表示不再等待接收客户端的连接请求
    tcp_server_socket.close()
